<template>
    <div class="ai-chat-container">
      <div class="chat-messages">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
        >
          <div class="avatar">
            <span>{{ message.role === 'user' ? '👤' : '🤖' }}</span>
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="isLoading" class="ai-message message">
          <div class="avatar">
            <span>🤖</span>
          </div>
          <div class="message-content">
            <div class="message-text">
              <div class="loading-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input-area">
        <button @click="quickChat" class="first-btn">快到期的护理项目</button>
  
  <!-- 第二行：输入框和发送按钮（用容器包裹，保持水平排列） -->
  <div class="second-row">
    <textarea
      v-model="userInput"
      placeholder="输入消息..."
      @keydown.enter="sendMessage"
      ref="inputRef"
    ></textarea>
    <button @click="sendMessage">发送</button>
  </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  
  // 状态管理
  const inputRef = ref(null);
  const userInput = ref('');
  const messages = ref([
    { 
      role: 'ai', 
      content: '你好！我是AI助手，有什么可以帮助你的吗？',
      timestamp: new Date()
    }
  ]);
  const isLoading = ref(false);
  
  // 发送消息
  const sendMessage = async () => {
  const content = userInput.value.trim();
  if (!content) return;
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content,
    timestamp: new Date()
  });
  userInput.value = '';
  
  // 聚焦输入框
  inputRef.value.focus();
  
  // 显示加载状态
  isLoading.value = true;
  
  try {
    // 调用实际API
    await getAIResponse(content);
  } catch (error) {
    console.error('API请求失败:', error);
    messages.value.push({
      role: 'ai',
      content: '抱歉，发生了错误，请重试。',
      timestamp: new Date()
    });
  } finally {
    isLoading.value = false;
  }
};
  
  // AI回复
  const getAIResponse = async (userMessage) => {
  try {
    // 1. 替换为后端实际运行的地址（协议+域名+端口）
    const backendBaseUrl = "http://localhost:9000";
    // 2. 构建带查询参数的完整URL
    const queryParams = new URLSearchParams({
      query: userMessage,
      style: "奶龙" // 传递风格参数
    }).toString();
    const requestUrl = `${backendBaseUrl}/chat?${queryParams}`;

    // 3. 发送POST请求（必须用POST，与后端@PostMapping匹配）
    const response = await fetch(requestUrl, {
      method: "POST", // 后端明确要求POST，必须指定
      headers: {
        // 不需要Content-Type: application/json（因为参数在Query中，非请求体）
        "Accept": "application/json" // 告诉后端期望返回JSON
      }
    });

    if (!response.ok) {
      throw new Error(`请求失败: 状态码 ${response.status}`);
    }

    // 4. 解析后端返回的字符串（你的后端直接返回String，无需JSON解析）
    const aiResponse = await response.text(); // 注意：用text()而非json()
    messages.value.push({
      role: "ai",
      content: aiResponse,
      timestamp: new Date()
    });
  } catch (error) {
    console.error("API请求错误:", error);
    messages.value.push({
      role: "ai",
      content: "抱歉，暂时无法连接到服务器，请稍后再试。",
      timestamp: new Date()
    });
  }
};

    const quickChat = async () => {
        const content = "快到期的护理项目，其中到期日期距离当前日期不超过一周视为快过期";
  messages.value.push({
    role: 'user',
    content,
    timestamp: new Date()
  });
  userInput.value = '';
  
  // 聚焦输入框
  inputRef.value.focus();
  
  // 显示加载状态
  isLoading.value = true;
        try{
            await getAIResponse(content);
        } catch (error) {
            console.error('API请求失败:', error);
            messages.value.push({
            role: 'ai',
            content: '抱歉，发生了错误，请重试。',
            timestamp: new Date()
            });
        } finally {
            isLoading.value = false;
        }
    }
  
  // 格式化时间
  const formatTime = (timestamp) => {
    return new Date(timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };
  
  // 组件挂载后聚焦输入框
  onMounted(() => {
    inputRef.value.focus();
  });
  </script>
  
  <style scoped>
  .ai-chat-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    border: 1px solid #ddd;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .message {
    display: flex;
    gap: 10px;
    max-width: 90%;
  }
  
  .user-message {
    align-self: flex-end;
    flex-direction: row-reverse;
  }
  
  .ai-message {
    align-self: flex-start;
  }
  
  .avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    flex-shrink: 0;
  }
  
  .message-content {
    background-color: #f0f0f0;
    padding: 10px 14px;
    border-radius: 18px;
    position: relative;
  }
  
  .user-message .message-content {
    background-color: #dcf8c6;
  }
  
  .message-text {
    font-size: 16px;
    margin-bottom: 4px;
  }
  
  .message-time {
    font-size: 12px;
    color: #888;
    text-align: right;
  }
  
  /* .chat-input-area {
    display: flex;
    gap: 10px;
    padding: 16px;
    border-top: 1px solid #ddd;
    background-color: #f8f8f8;
  } */

  .chat-input-area {
  /* 关键：改为垂直排列的flex容器 */
  display: flex;
  flex-direction: column; /* 子元素垂直排列 */
  gap: 10px; /* 两行之间的间距 */
  padding: 16px;
  border-top: 1px solid #ddd;
  background-color: #f8f8f8;
}

/* 第二行容器：保持输入框和发送按钮水平排列 */
.second-row {
  display: flex; /* 子元素水平排列 */
  gap: 10px; /* 输入框和按钮的间距 */
}

/* 第一行按钮样式（可选：调整宽度适应内容） */
.first-btn {
  align-self: flex-start; /* 按钮宽度适应内容，不占满整行 */
}
  
  textarea {
    flex: 1;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 20px;
    resize: none;
    font-size: 16px;
    outline: none;
  }
  
  button {
    background-color: #07c160;
    color: white;
    border: none;
    border-radius: 20px;
    padding: 10px 20px;
    cursor: pointer;
    font-size: 16px;
    white-space: nowrap;
  }
  
  button:hover {
    background-color: #06b056;
  }
  
  .loading-indicator {
    display: flex;
    gap: 4px;
    height: 20px;
  }
  
  .loading-indicator span {
    width: 5px;
    height: 5px;
    background-color: #666;
    border-radius: 50%;
    animation: bounce 1.4s infinite ease-in-out both;
  }
  
  .loading-indicator span:nth-child(1) { animation-delay: -0.32s; }
  .loading-indicator span:nth-child(2) { animation-delay: -0.16s; }
  
  @keyframes bounce {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1); }
  }
  </style>  